package tcp;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/17
 * Time:15:56
 **/
public class Client {
    /**
     * 客户端-"智能" 翻译机器人
     */
    //服务器IP
    private static final String ip = "127.0.0.1";
    //服务器端口号
    private static final int port = 1001;

    public static void main(String[] args) throws IOException {
        //1.启动客户端，连接服务器端
        Socket socket = new Socket(ip, port);
        System.out.println("客户端已启动！");

        //2.创建收发消息对象
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())
        );
             BufferedReader reader = new BufferedReader(
                     new InputStreamReader(socket.getInputStream())
             );
             Scanner scanner = new Scanner(System.in);
        ) {
            while (true) {
                System.out.println("English:");

                //3.发送消息
                String msg = scanner.nextLine();
                writer.write(msg + "\n");//不能省略\n
                writer.flush();// 将发送缓冲区的消息立即发送

                //4.接收服务器返回的消息
                String serMsg = reader.readLine();
                if (serMsg != null && !serMsg.equals("")) {
                    System.out.println("翻译结果为：" + serMsg);
                }
            }
        }
    }
}
